<template>
  <view class="showTalks" @click.stop="useless=null">
    <view class="header">
      <view class="header-left" @click.stop="changeShowTalks">×</view>
      <view class="header-right">所有评论</view>
    </view>
    <!-- 评论列表 -->
    <scroll-view @scrolltolower="scrolltolower"  class="listCont" scroll-y v-if="commendList.length>0">
      <div class="listItem" v-for="(item,index) in commendList" :key="index">
        <div class="leftCont" @click="goToUserDefault(item)"> 
          <img :src="item.head_pic?item.head_pic:'/static/image/user.png'" alt="">
        </div>
        <div class="rightCont">
          <div class="topInfo" @click="goToUserDefault(item)">
            <!-- <div class="userName">{{item.nickname?item.nickname:"**用户"}} -->
              <div class="userName">{{item.is_anonymous?"xxx":item.nickname}}
              <img src="/static/image/guanfang-vip.png" alt="" style="width:48rpx;height:28rpx;margin-left:12rpx;vertical-align: middle;" v-if="item.role==3">
              <img src="/static/image/vip-sign.png" alt="" style="width:48rpx;height:28rpx;margin-left:12rpx;vertical-align: middle;" v-if="item.role==2"> 
            </div>
            <div class="dispatchTime">{{index+1}}楼 {{item.create_time}}</div>
          </div>
          <div class="bottomCont">
            <div class="bottomInfo" @click="replyComment(item)">
              <i style="display:block;">
                <div v-if="item.rnickname" style="display:inline-block;">
                  <i  style="display:inline-block;">回复</i>
                  <span style="color:#FF5470;display:inline-block;">{{item.is_ranonymous?"xxx":item.rnickname}}</span>
                  <i style="display:inline-block;">: </i>
                </div>
                {{item.content}}
              </i>
            </div>
            <div class="thumbsBtn"  @click="thumb(item,index,'')">
              <img v-if="item.is_like" src="/static/image/good-active.png" alt="">
              <img v-else src="/static/image/good.png" alt="">
              <span>{{item.liked_cnt}}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 以上是全部评论||正在加载更多 -->
      <div v-if="commendList.length>0">
        <div class="endBox" v-if="isLoad">{{isEnd?'以上是全部评论':'正在加载更多'}}</div>
      </div>
    </scroll-view>
    <div class="noData" v-else>
      <img src="/static/image/sofa.png"/>
      <div class="asideWord">暂无评论，快来说两句…</div>
    </div>

    <block  v-if="is_login"> 
      <!-- <div class="blank"></div> -->
      <div class="footDispatch" :style="'bottom:'+writeHeight+'px'">
        <input type="text" v-model="currentComment" maxlength="200" :adjust-position="false" :focus="isFocus" @blur="inputBlur" @focus="inputFocus($event)" :placeholder="replyPlaceHolder" confirm-type="send" :show-confirm-bar="false" @confirm="sendComment">
        <!-- <div class="anonymousBtn" @click.stop="checkAnoy">
            <label class="checkbox">
                <span class="checkBtn">
                  <img v-if="isAnonymous" src="/static/image/check-btn.png" alt="">
                </span>
                xxx
            </label>
        </div> -->
        <div class="dispatchBtn" v-if="currentComment.length>0" @click="sendComment">发布</div>
      </div>
    </block>
  </view>
</template>

<script> 
import * as api from '@/utils/api' ;    
import headBack from '@/components/head-back.vue' ;     
import newsList from '@/components/news-list.vue' ;   
import newsStore from './../pages/common/news/store' ; 
import loginNull from '@/components/login-null.vue' ;    
const app = getApp();  
export default { 
  onLoad(opt){       
    let vm = this;   
    if(newsStore.state.newsDataItem!={}) {
      vm.newData=newsStore.state.newsDataItem;
    } 
    this.commentListInfo.article_id=this.artId;
    this.clearListData();
    this.getHotCommendList();
    this.getCommentList();
  },
  onReady(){
    if(wx.getStorageSync('refresh_token')&&wx.getStorageSync('token')&&wx.getStorageSync('is_tourist')==2){
      this.is_login=true;  
      this.modalShow=false; 
    } else { 
      this.is_login=false;    
    }
  },
  onShow(){
    if(wx.getStorageSync('refresh_token')&&wx.getStorageSync('token')&&wx.getStorageSync('is_tourist')==2){
      this.is_login=true;  
      this.modalShow=false; 
    } else { 
      this.is_login=false;    
    }
  },
  components:{ 
    headBack,
    newsList,
    loginNull, 
  }, 
  props:['artId'],
  data () {
    return {       
      headHeight:wx.getStorageSync('headHeight'),
      headPadding:wx.getStorageSync('headPadding'),  
      newData:{},//获取详情信息
      commenedNum:0,//评论数量
      hotCommendList:[],//置顶评论
      commendList:[],//评论列表
      currentComment:'',//输入的评论
      commentListInfo:{
        is_time:0,
        article_id:null,
        page:1,
        size:10,
        total_page:0,
      },//请求评论列表参数
      isLoad:false,//是否在加载
      isEnd:false,//是否加载了所有评论
      isAnonymous:false,
      isFocus:false,
      writeHeight:0,
      is_login:false,
      modalShow:false,
      dispatchData:{
        is_ranonymous:false,
        ruuid:'',
        comment_id:0,
      },
      rname:'',
      replyPlaceHolder: '说两句...'
    }
  },  
  methods: { 
    changeShowTalks(){
      this.$parent.notShowTalks()
    },
    //评论点赞
    thumb(item,index,isHot){
      let me=this;
      if(!this.is_login){
        this.modalShow=true;
        return;
      }
      if(!item.is_like){
        api.commendThum({
          comment_id:item.comment_id,
          is_like:1,
        }).then(
          (res)=>{
            if(res.data.code==300000){
              let newItem=item;
              newItem.is_like=1;
              newItem.liked_cnt++;
              setTimeout(()=>{
                if(isHot=='hot'){
                  me.hotCommendList.splice(index,1,newItem);
                }else{
                  me.commendList.splice(index,1,newItem);
                }
              },500);
            }
          }
        )
      }else{
        api.commendThum({
          comment_id:item.comment_id,
          is_like:0,
        }).then(
          (res)=>{
            if(res.data.code==300000){
              let newItem=item;
              newItem.is_like=0;
              newItem.liked_cnt--;
              setTimeout(()=>{
                if(isHot=='hot'){
                  me.hotCommendList.splice(index,1,newItem);
                }else{
                  me.commendList.splice(index,1,newItem);
                }
              },500);
            }
          }
        )
      }
    },
    //排序按钮
    sortFixed(){
      this.commentListInfo.is_time==0?this.commentListInfo.is_time=1:this.commentListInfo.is_time=0;
      this.getCommentList('fresh');
    },
    //回复评论
    replyComment(item){
      if(!this.isFocus){
        this.isFocus=true;
        if(item.is_anonymous) {
          this.rname = 'xxx'
        } else {
          this.rname = item.nickname
        }
        
        this.replyPlaceHolder = '回复：' + this.rname
      }
      this.dispatchData={
        is_ranonymous:item.is_anonymous,
        ruuid:item.uuid,
        comment_id:item.comment_id,
      };
    },
    //获取热门列表
    getHotCommendList(){
      api.getHotCommendList({
        article_id:this.commentListInfo.article_id,
        size:10,
      }).then(
        (res)=>{
          let resData=res.data.data; 
          if(res.data.code==300000&&resData.data){ 
            this.hotCommendList=[];
            for(let i=0;i<resData.data.length;i++){
              resData.data[i].create_time=this.getDateDiff((resData.data)[i].create_at);
            }
            this.hotCommendList=resData.data.slice(0,10);
          } 
        },
        (err)=>{
          console.log(err);
        }
      )
    },

    //选择或取消xxx
    // checkAnoy(){
    //     this.isAnonymous=!this.isAnonymous;
    //     this.isFocus=false;
    // },  
    goBack(){   
      //清除数据
      this.clearData();
      newsStore.commit('clearItem');
      wx.navigateBack({ delta: 1 });
    }, 
    //清除所有数据
    clearData(){
      this.newData={};
      this.commenedNum=0;
      this.commendList=[];
      this.currentComment='';
      this.commentListInfo={
        article_id:null,
        page:1,
        size:10,
        total_page:0,
      };
      this.isLoad=false;
      this.isEnd=false;
      this.isAnonymous=false;
      this.dispatchData={
        is_ranonymous:false,
        ruuid:'',
        comment_id:0,
      };
      this.hotCommendList=[];
    },  
    //清除评论列表的数据
    clearListData(){
      this.commendList=[];
      this.commenedNum=0;
      this.commentListInfo.page=1;
      this.commentListInfo.size=10;
      this.commentListInfo.total_page=0;
      this.isLoad=false;
      this.isEnd=false;
      this.isAnonymous=false;
      this.dispatchData={
        is_ranonymous:false,
        ruuid:'',
        comment_id:0,
      };
    },
    //计算虚拟dom的参数
    computeDom(dom){
      return new Promise(function (resolve, reject) {
        var query = wx.createSelectorQuery();
        query.select(dom).boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec((res) => {
          resolve(res[0]);
        });
      });
    },
    //获取评论列表
    getCommentList(fresh){
      if(fresh=='fresh'){
        this.clearListData();
      };
      return api.videoCommentList(this.commentListInfo).then(
        (res)=>{
          let resData=res.data.data; 
          if(res.data.code==300000&&resData.data){ 
            this.commentListInfo.total_page=resData.info.total_page;
            this.commenedNum=resData.info.total;
            newsStore.state.newsDataItem.reply_cnt=this.commenedNum;
            for(let i=0;i<resData.data.length;i++){
              resData.data[i].create_time=this.getDateDiff((resData.data)[i].create_at);
            }
            this.commendList.push(...resData.data);
          } 
        },
        (err)=>{
          console.log(err);
        }
      );
    },
    //发布评论
    dispatchComment(){
      if(this.currentComment.trim()==''){
        wx.showModal({
            title: '提示',
            content: '请输入有效的内容',
            showCancel: false
        });
      }else if(this.currentComment.trim().length>180){
        wx.showModal({
            title: '提示',
            content: '最多输入180个字',
            showCancel: false
        });
      }else{
        return api.dispatchComment({
          ruuid:this.dispatchData.ruuid,
          article_id:this.artId,
          content:this.currentComment,
          is_anonymous:this.isAnonymous,
          is_ranonymous:this.dispatchData.is_ranonymous,
          // comment_id:700,
        }).then(
          ({data})=>{
            if(data.code==300000){
              this.currentComment='';
              // newsStore.state.newsDataItem.reply_cnt++;
              wx.showToast({
                title: '评论成功',
                icon: 'success',
                duration: 1000
              });
              this.rname = '',
              this.replyPlaceHolder =  '说两句...'
              //滚动到评论位置
              // this.computeDom('.newsList').then(
              //   (res)=>{
              //     wx.pageScrollTo({
              //       scrollTop:res.height
              //     })
              //   }
              // );
              // 成功发布评论获取列表
              setTimeout(()=>{
                // this.clearData();
                this.getCommentList('fresh').then(
                  ()=>{
                    this.isLoad=false;
                  }
                );
              },1000);
            }else if(data.code== 300120){
              wx.showModal({
                title: "提示",
                content: "发布含有违法违规内容，请重新编辑上传",
                showCancel: false
              });
            }
          },
          (err)=>{
            wx.showToast({
              title: '评论失败',
              icon: 'warn',
              duration: 1000
            })
            console.log(err);
          }
        )
      }
    },
    //发送评论
    sendComment(){
      this.dispatchComment();
    },
    leaveWord(item,str){
      this.dispatchData={
        is_ranonymous:false,
        ruuid:'',
        comment_id:0,
      };
      if(str=='setWords'){
        if(!this.is_login){
          this.modalShow=true;
          return;
        }
        if(!this.isFocus){
          this.isFocus=true;
        }
      } 
    },
    inputBlur(){
      this.isFocus=false;
      this.writeHeight=0;

      if(this.currentComment.length === 0) {
        this.rname = ''
        this.replyPlaceHolder = '说两句...'

        this.dispatchData={
          is_ranonymous:false,
          ruuid:'',
          comment_id:0,
        };
      }
      
    },
    inputFocus(e){
      this.isFocus=true;
      this.writeHeight=e.mp.detail.height;
      // this.writeHeight=0;
    },
    //跳转用户资料
    goToUserDefault(item){
      let meRuuid = JSON.parse(wx.getStorageSync('account')).uuid;
      if(!this.is_login){
        this.modalShow=true;
        return;
      }
      if(!item.is_anonymous&&meRuuid!==item.uuid){
        wx.navigateTo({url:`./../../common/user-detail-page/main?ruuid=${item.uuid}`});
      }
    },
    //用户未登录
    checkIsLogin(){
      this.modalShow=true;
    },
    //关闭登录框
    closeModal(){
      this.modalShow=false;
    },
    //触底事件
    scrolltolower(){
      if(!this.isLoad){
        if(this.commentListInfo.page>=this.commentListInfo.total_page){
          this.isLoad=true;
          this.isEnd=true;
          return
        }else{
          this.isLoad=true;
          this.commentListInfo.page+=1;
          this.getCommentList().then(
            ()=>{
              this.isLoad=false;
            }
          );
        }
      }else{
        return;
      };
    },
  },
  
  onShareAppMessage: function(res) {  
    let meRuuid = JSON.parse(wx.getStorageSync('account')).uuid; 
    let title = `${this.newData.content}`;
    let imgLink = this.newData.pics?this.newData.pics[0]:'';
    let path = `pages/common/index/main?sharRuuid=${meRuuid}&artId=${this.newData.art_id}&type=news`;   
    return this.onShareAppMessage(title,path,imgLink);
  },  
}
</script>

<style lang="scss" scoped>
  .showTalks {
    width: 100%;
    height: 75vh;
    background-color:rgba(255,255,255,1);
    border-radius:32rpx 32rpx 0 0;

    .header {
      height: 100rpx;
      line-height: 100rpx;
      width: 100%;
      position: fixed;
      top: 25vh;

      .header-left {
        box-sizing: border-box;
        float: left;
        width: 240rpx;
        color: #808892;
        font-size: 60rpx;
        padding-left: 54rpx;

      }

      .header-right {
        box-sizing: border-box;
        width: 410rpx;
        text-align: center;
        float: left;
        color: #1D2438;
        font-size: 30rpx;
        margin-left: -64rpx;
      }
    }

  }
  .listCont{
      height: 100%;
      padding: 100rpx 0;
      box-sizing: border-box;

      .listItem{
          padding-left: 32rpx;
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          padding-top:34rpx;
          .leftCont{
              width: 72rpx;
              height:64rpx;
              margin-right: 12rpx;
              border-radius: 50%;
              border:1px solid #f0f0f0;
              img{
                  width: 100%;
                  height: 100%;
                  border-radius: 50%;
              }
          }
          .rightCont{
              width: 100%;
              .topInfo{
                  .userName{
                      font-size:26rpx;
                      font-family:PingFangSC-Regular;
                      font-weight:400;
                      color:rgba(29,36,56,1);
                  }
                  .dispatchTime{
                      font-size:22rpx;
                      font-family:PingFangSC-Regular;
                      font-weight:400;
                      color:rgba(145,149,159,1);
                  }
              }
              .bottomCont{
                  display: flex;
                  align-items: flex-start;
                  justify-content: space-between;
                  font-size:30rpx;
                  font-family:PingFangSC-Regular;
                  font-weight:400;
                  color:rgba(29,36,56,1);
                  line-height:42rpx;
                  padding-top:24rpx;
                  padding-bottom: 34rpx;
                  border-bottom: 1px dashed #E1E6EB;
                  box-sizing: border-box;
                  padding-right:24px;
                  .bottomInfo{
                    width:100%;
                  }    
                  .thumbsBtn{
                    box-sizing: border-box;
                    min-width: 110rpx;
                    display: flex;
                    justify-items: center;
                    align-items: center;
                    padding-left: 40rpx;
                      img{
                        display: inline-block;
                        width: 45rpx;
                        height:42rpx;
                        margin-right:10rpx;

                      }
                      span{
                        font-size:24rpx;
                        font-family:Helvetica;
                        color:rgba(128,136,146,1);
                        line-height:28rpx;
                        margin-left:6rpx;
                      }
                  }
              }
              
          }
      }
      .listItem:last-child{
        .rightCont{
          .bottomInfo{
            border-bottom: none;
          }
        }
      }
  }

  .noData{
    height: 100%;
    text-align:center;
    img{
      display: block;
      width: 242rpx;
      height: 200rpx;
      margin: 0 auto;
      padding-top:182rpx;
    }
    .asideWord{
      width: 100%;
      font-size:24rpx;
      font-family:PingFangSC-Regular;
      font-weight:400;
      color:rgba(128,136,146,1);
      line-height:34rpx;
      margin-top:38rpx;
      padding-bottom: 118rpx;
    }
  }

  .endBox{
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background: #f0f0f0;
    text-align: center;
    font-size: 28rpx;
    color: #999;
  }

  // .blank{
  //   height: 100rpx;
  // }

  .footDispatch{
    width:100%;
    height: 100rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    box-sizing: border-box;
    padding:0 20rpx;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 12px 0px rgba(53,64,82,0.19);
    overflow: hidden;
    opacity: 0.95;
    border:1px solid #fff;
    input{
        display: block;
        flex: 1;
        height: 100%;
        line-height: 100rpx;
        font-size:28rpx;
        font-family:PingFangSC-Regular;
        font-weight:400;
        color:rgba(145,149,159,1);
        padding-right:10rpx;
        box-sizing: border-box;
    }
    .anonymousBtn{
        min-width: 156rpx;
        height:48rpx;
        background:rgba(255,255,255,1);
        border-radius:28px;
        border:1px solid rgba(187,190,194,1);
        font-size: 24rpx;
        color:rgba(145,149,159,1);
        margin-left:21rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right:16rpx;
        .checkbox{
            display: flex;
            justify-content: center;
            align-items: center;
            .checkBtn{
                display: block;
                width:28rpx;
                height:28rpx;
                background:rgba(255,255,255,1);
                border-radius:28rpx;
                margin-right:12rpx;
                border:1px solid rgba(145,149,159,1);
                overflow: hidden;
                box-sizing: border-box;
                img{
                    display: block;
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }
    .dispatchBtn{
        min-width: 134rpx;
        height: 64rpx;
        text-align: center;
        line-height: 64rpx;
        background:linear-gradient(34deg,rgba(255,120,73,1) 0%,rgba(255,65,120,1) 100%) rgba(255,255,255,0.42);
        border-radius:32rpx;
        font-size:28rpx;
        font-family:PingFangSC-Regular;
        font-weight:400;
        color:rgba(255,255,255,1);
    }
  }
</style>
